package com.example.lanouhn.firstapp.activity.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.ClassifyNappyAdapter;
import com.example.lanouhn.firstapp.activity.adapter.NappyPantsAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.fragment.ClassifyFragment;
import com.example.lanouhn.firstapp.activity.fragment.HomePageFragment;
import com.example.lanouhn.firstapp.activity.fragment.MineFragment;
import com.example.lanouhn.firstapp.activity.fragment.ShoppingCarFragment;
import com.example.lanouhn.firstapp.activity.model.Classify;
import com.example.lanouhn.firstapp.activity.model.NappyPants;
import com.example.lanouhn.firstapp.activity.utils.ClassifyJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.utils.NappyPantsJson;
import com.example.lanouhn.firstapp.activity.view.xlistview.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 二级点击跳转到本页面
 * 分类下的三级解析的主布局
 * 例如：各种品牌纸尿裤、奶粉等等的图文详情页面
 */
public class NappyPantsActivity extends AppCompatActivity {
    //设置变量
    private XListView listView;
    private RadioGroup radioGroup;

    private NappyPantsAdapter adapter;
    //定义集合
    private List<NappyPants> dataList;

    //一个中间量集合
    private List<NappyPants> tempList;


    private String gc_id;
    //加载进度
    private ProgressBar progressBar;

    //排序类型
    private int key = 4;
    //页容量
    private int pageSize = 10;
    //当前页
    private int currentPage = 1;
    //升降序标识
    private boolean orderFlag = true;
    private int order = 1;//升序1，降序2

    //判断是否是第一次启动，只显示一次progressBar
    private boolean isFirstRequest = true;

    //设置返回键
    private ImageView back;
    //点击下部标识返回主页的四个Fragment的
    private RadioGroup radioGroup_bottom;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nappy_pants);

        //获取上个页面传过来的参数
        gc_id = getIntent().getStringExtra("gc_id");

        //找控件
        listView = (XListView) findViewById(R.id.listView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        back = (ImageView) findViewById(R.id.imageview_left);
        radioGroup_bottom = (RadioGroup) findViewById(R.id.radioGroup_bottom);
        //开启加载更多功能 设置上拉加载的开关
        listView.setPullLoadEnable(true);
        //创建新线程，请求网络数据并解析
        getDateFromWeb();
        //设置item的点击事件
        onItemClickListener();

    }

    private void onItemClickListener() {
        //        radioGroup点击事件
        radioGroup_bottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Intent it = new Intent();
                switch (i){
                    case R.id.rb_homePager:
                        it.setClass(NappyPantsActivity.this, MainActivity.class);
                        it.putExtra("symbol",1);
                        startActivity(it);
                        break;
                    case R.id.rb_classify:
                        it.setClass(NappyPantsActivity.this, MainActivity.class);
                        it.putExtra("symbol",2);
                        startActivity(it);
                        break;
                    case R.id.rb_shoppingCar:
                        it.setClass(NappyPantsActivity.this, MainActivity.class);
                        it.putExtra("symbol",3);
                        startActivity(it);
                        break;
                    case R.id.rb_personCenter:
                        it.setClass(NappyPantsActivity.this, MainActivity.class);
                        it.putExtra("symbol",4);
                        startActivity(it);
                        break;
                }

            }

        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //默认RB
        radioGroup.check(R.id.rb_newGoods);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                switch (i) {
                    case R.id.rb_newGoods://新品key=4
                        key = 4;
                        break;
                    case R.id.rb_price://价格key=3
                        key = 3;
                        if (orderFlag)
                            order = 1;
                        else
                            order = 2;

                        orderFlag = !orderFlag;
                        break;
                    case R.id.rb_sellNumber://销量key=2
                        key = 2;
                        break;
                    case R.id.rb_popularity://人气key=1
                        key = 1;
                        break;
                }
                //重新获取数据并填充listView
                getDateFromWeb();

            }
        });
        //实现listView的刷新加载监听
        listView.setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {

                //下拉刷新
                currentPage = 1;
                getDateFromWeb();
            }

            @Override
            public void onLoadMore() {

                //上拉更多
                currentPage++;
                getMoreDataFromWeb();
            }
        });


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //跳转到下个页面并传递参数
                Intent intent = new Intent(NappyPantsActivity.this,GoodsDetailsActivity.class);
//                携带goods_id  跳转到下个页面
                intent.putExtra("goods_id",dataList.get(i).getGoods_id());
                startActivity(intent);
            }
        });
    }

    /**
     * 获取更多列表数据
     */
    private void getMoreDataFromWeb() {


        tempList = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {

                String result = HttpUtils.doGet(getRequestUrl());

                if (!result.equals("") && !result.equals("null")) {

                    //解析JSON数据
                    tempList = NappyPantsJson.getNappyPants(result);
                    if (tempList.size() > 0)
                        handler.sendEmptyMessage(2);
                    else
                        handler.sendEmptyMessage(0);

                } else {
                    //提示用户网络连接失败
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();


    }


    /**
     * 获取列表数据
     */
    private void getDateFromWeb() {
        //显示加载进度条
        if (isFirstRequest)
            progressBar.setVisibility(View.VISIBLE);

        /**
         * 开启线程
         */
        dataList = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {

                String result = HttpUtils.doGet(getRequestUrl());

                if (!result.equals("") && !result.equals("null")) {

                    //解析JSON数据
                    dataList = NappyPantsJson.getNappyPants(result);
                    if (dataList.size() > 0)
                        handler.sendEmptyMessage(1);
                    else
                        handler.sendEmptyMessage(0);

                } else {
                    //提示用户网络连接失败
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();

        isFirstRequest = false;

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //影藏进度条
            progressBar.setVisibility(View.GONE);

            switch (msg.what) {
                case 0://请求解析失败
                    Toast.makeText(NappyPantsActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 1://请求解析成功
                    adapter = new NappyPantsAdapter(dataList, NappyPantsActivity.this);
                    listView.setAdapter(adapter);

                    listView.stopRefresh();
                    listView.setPullLoadEnable(true);
                    break;
                case 2://请求更多数据成功

                    //添加到原来的集合
                    String goodsId = tempList.get(0).getGoods_id();
                    //判断原来集合中是否存在当前id

                    List<String> ids = new ArrayList<>();
                    for (int i = 0; i < dataList.size(); i++) {
                        ids.add(dataList.get(i).getGoods_id());
                    }

                    if (ids.contains(goodsId)) {
                        //已经没有新数据了
                        Toast.makeText(NappyPantsActivity.this, "已经是最后一页啦！", Toast.LENGTH_SHORT).show();
                        //取消上拉加载更多
                        listView.setPullLoadEnable(false);
                    } else {
                        dataList.addAll(tempList);
                    }

                    //刷新页面
                    adapter.notifyDataSetChanged();
                    //清空中间量集合
                    tempList.removeAll(tempList);
                    //停止加载
                    listView.stopLoadMore();
                    break;
            }
        }
    };


    /**
     * 获取请求地址
     *
     * @return
     */
    private String getRequestUrl() {
        return Constants.GOODSLIST_TOTAL + "&key=" + key + "&page=" + pageSize + "&curpage=" + currentPage + "&gc_id=" + gc_id + "&order=" + order;
    }
}
